package org.apache.tomcat.maven.plugin.tomcat9.run;

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.tomcat.maven.common.run.EmbeddedRegistry;
import org.apache.tomcat.maven.plugin.tomcat9.AbstractTomcat9Mojo;

import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.Socket;


/**
 * <p>
 * Shuts down all possibly started embedded Tomcat servers. This will be automatically done
 * through a shutdown hook or you may call this Mojo to shut them down explictly.
 * </p>
 * <p>
 * By default the <code>shutdown</code> goal is not bound to any phase. For integration tests
 * you might want to bind it to <code>post-integration-test</code>.
 * </p>
 *
 * @author Mark Michaelis
 * @since 2.0
 */
@Mojo(name = "shutdown", requiresDependencyResolution = ResolutionScope.RUNTIME, threadSafe = true)
public class ShutdownMojo
        extends AbstractTomcat9Mojo {

    /**
     * Ignore error when shutdown
     *
     * @since 2.0
     */
    @Parameter(property = "maven.tomcat.skipErrorOnShutdown", defaultValue = "false")
    protected boolean skipErrorOnShutdown;

    /**
     * Skip execution
     *
     * @since 2.0
     */
    @Parameter(property = "maven.tomcat.skipShutdown", defaultValue = "false")
    protected boolean skip;

    @Parameter(property = "maven.tomcat.stopPort", defaultValue = "8005")
    protected int stopPort;

    @Parameter(property = "maven.tomcat.stopWait", defaultValue = "0")
    protected int stopWait;

    /**
     * Shuts down all embedded tomcats which got started up to now.
     *
     * @throws org.apache.maven.plugin.MojoExecutionException if shutting down one or all servers failed
     */
    @Override
    public void execute()
            throws MojoExecutionException {
        if (skip) {
            getLog().info("skip execution");
            return;
        }
        getLog().info("Stop Tomcat to port:"+stopPort);
        try (Socket s = new Socket(InetAddress.getByName("127.0.0.1"), stopPort);)
        {
            OutputStream out = s.getOutputStream();
            out.write(("SHUTDOWN").getBytes());
            out.flush();

            if (stopWait > 0)
            {
                s.setSoTimeout(stopWait * 1000);
                s.getInputStream();

                getLog().info("Waiting " + stopWait + " seconds for Tomcat to stop");
                LineNumberReader lin = new LineNumberReader(new InputStreamReader(s.getInputStream()));
                String response;
                boolean stopped = false;
                while (!stopped && ((response = lin.readLine()) != null))
                {
//                    if ("Stopped".equals(response))
//                    {
//                        stopped = true;
//                        getLog().info("Server reports itself as stopped");
//                    }
                    getLog().info("Server stopped:"+response);
                }
            }
        }
        catch (ConnectException e)
        {
            getLog().info("Tomcat not running!");
        }
        catch (Exception e)
        {
            getLog().error(e);
        }
//        try {
//            EmbeddedRegistry.getInstance().shutdownAll(getLog());
//        } catch (Exception e) {
//            if (!skipErrorOnShutdown) {
//                throw new MojoExecutionException(messagesProvider.getMessage("ShutdownMojo.shutdownError"), e);
//            }
//        }
    }
}
